import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uuid/uuid.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_sound/flutter_sound.dart' hide PlayerState;
import 'package:audioplayers/audioplayers.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'dart:io';
import '../models/note.dart';
import '../models/folder.dart';
import '../service/database_service.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';

class NoteEditPage extends StatefulWidget {
  final Note? note; 

  const NoteEditPage({super.key, this.note});

  @override
  State<NoteEditPage> createState() => _NoteEditPageState();
}

class _NoteEditPageState extends State<NoteEditPage> {
  final _titleController = TextEditingController();
  final _contentController = TextEditingController();
  final _labelController = TextEditingController();
  final _databaseService = DatabaseService();
  final _imagePicker = ImagePicker();
  final _recorder = FlutterSoundRecorder();
  bool _isPinned = false;
  bool _isRecording = false;
  String? _selectedFolderId;
  List<Folder> _folders = [];
  List<String> _imagePaths = [];
  List<String> _audioPaths = [];
  String? _currentRecordingPath;
  String? _currentPlayingPath;
  final _speech = SpeechToText();
  bool _isListening = false;
  String _lastWords = '';
  String _recognizedText = '';
  File? _imageFile;
  final  _player = AudioPlayer(); 
  final _textRecognizer = TextRecognizer(script: TextRecognitionScript.chinese);

  @override
  void initState() {
    super.initState();
    if (widget.note != null) {
      _titleController.text = widget.note!.title;
      _contentController.text = widget.note!.content;
      _labelController.text = widget.note!.label ?? '';
      _isPinned = widget.note!.isPinned;
      _selectedFolderId = widget.note!.folderId ?? '-1111';
      _imagePaths = List.from(widget.note!.imagePaths);
      _audioPaths = List.from(widget.note!.audioPaths);
    } 
    _loadFolders(); 
    _checkPermissions(); 
    _initRecorder(); 
    _initplayer();
    _initSpeech();
  }

  Future<void> _loadFolders() async {
    try {
      final folders = await _databaseService.getAllFolders();
      setState(() {
        _folders = folders;
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载文件夹失败: $e')),
        );
      }
    }
  }

  Future<void> _checkPermissions() async {
    await Permission.camera.request();
    await Permission.microphone.request();
    await Permission.storage.request();
    await Permission.speech.request();
  }

  Future<void> _initRecorder() async {
    await _recorder.openRecorder();
  }

  Future<void> _initplayer() async {
    _player.onPlayerStateChanged.listen((state) {
      if (state == PlayerState.completed || state == PlayerState.disposed) {
        setState(() {
          _currentPlayingPath = null;
        });
      }
    });
  }

  Future<void> _initSpeech() async {
    try {
      await _speech.initialize(
        onStatus: (status) {
          if (status != 'listening') {
            setState(() {
              _isListening = false;
            });
          }
        },
        onError: (error) {
          setState(() {
            _isListening = false;
          });
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('语音识别错误: $error')),
            );
          }
        },
      );
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('初始化失败:$e')),
        );
      }
    }
  }

  Future _selectFolder() async {
    final result = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择文件夹'),
        content: SizedBox(
          width: double.maxFinite,
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: _folders.length + 1,
            itemBuilder: (context, index) {
              if (index == 0) {
                return ListTile(
                  leading: const Icon(Icons.folder, color: Colors.yellow,),
                  title: const Text('其他'),
                  onTap: () => Navigator.pop(context, "-1111"),
                );
              }
              final folder = _folders[index - 1];
              return ListTile(
                leading: const Icon(Icons.folder, color: Colors.yellow,),
                title: Text(folder.name),
                onTap: () => Navigator.pop(context, folder.id),
              );
            },
          ),
        ),
      ),
    );
    
    setState(() {
      _selectedFolderId = result;
    });
  }

  Future<void> _saveNote() async {
    final note = Note(
      id: widget.note?.id ?? const Uuid().v4(),
      title: _titleController.text,
      content: _contentController.text,
      label: _labelController.text,
      createdAt: widget.note?.createdAt ?? DateTime.now(),
      updatedAt: DateTime.now(),
      isPinned: _isPinned,
      password: widget.note?.password,
      folderId: _selectedFolderId,
      imagePaths: _imagePaths,
      audioPaths: _audioPaths,
    );

    try {
      if (widget.note == null) {
        await _databaseService.insertNote(note);
      } else {
        await _databaseService.updateNote(note);
      }
      if (mounted) {
        Navigator.pop(context, note);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('保存笔记失败: $e')),
        );
      }
    }
  }

  Future<ImageSource?> _showImageSourceDialog() async {
    final result = await showDialog(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('选择图片来源'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.camera_alt),
              title: const Text('拍照'),
              onTap: () => Navigator.pop(context, ImageSource.camera),
            ),
            ListTile(
              leading: const Icon(Icons.photo_library),
              title: const Text('从相册选择'),
              onTap: () => Navigator.pop(context, ImageSource.gallery),
            ),
          ],
        ),
      ),
    );

    return result;
  }

  Future<void> _pickImage(ImageSource source) async {
    try {
      final image = await _imagePicker.pickImage(source: source);
      if (image != null) {
        setState(() {
          _imagePaths.add(image.path);
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择图片失败: $e')),
        );
      }
    }
  }

  void _removeImage(int index) {
    setState(() {
      _imagePaths.removeAt(index);
    });
  }

  Future<void> _startRecording() async {
    try {
      final dir = await getTemporaryDirectory();
      _currentRecordingPath = path.join(
        dir.path,
        'recording_${DateTime.now().millisecondsSinceEpoch}.aac',
      );

      await _recorder.startRecorder(
        toFile: _currentRecordingPath,
        codec: Codec.aacADTS,
      );

      setState(() {
        _isRecording = true;
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('开始录音失败: $e')),
        );
      }
    }
  }

  Future<void> _stopRecording() async {
    try {
      await _recorder.stopRecorder();
      if (_currentRecordingPath != null) {
        setState(() {
          _audioPaths.add(_currentRecordingPath!);
          _isRecording = false;
          _currentRecordingPath = null;
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('停止录音失败: $e')),
        );
      }
    }
  }

  Future<void> _playAudio(String path) async {
    try {
      await _player.play(DeviceFileSource(path));
    } catch (e) {
      setState(() {
        _currentPlayingPath = null;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('播放音频失败: $e')),
        );
      }
    }
  }

  void _removeAudio(int index) {
    setState(() {
      _audioPaths.removeAt(index);
    });
  }

  Future<void> _startListening() async {
    _lastWords = '';
    try {
      setState(() { _isListening = true; });
      await _speech.listen(
        onResult: (result) {
          setState(() {
            _lastWords = result.recognizedWords;
            if (result.finalResult) {
              _isListening = false;
              _contentController.text += ' ' + _lastWords;
            }
          });
        },
        localeId: 'zh_CN', 
      );
    } catch (e) {
        setState(() {
          _isListening = false;
        });
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('开始语音识别失败: $e')),
          );
        }
    }
  }

  void _stopListening() async {
    try {
      await _speech.stop();
      setState(() {
        _isListening = false;
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('停止语音识别失败: $e')),
        );
      }
    }
  }

  Future<void> _recognize(ImageSource source) async {
    final image = await _imagePicker.pickImage(source: source);
    if (image != null) {
      _imageFile = File(image.path);
    } else {
      return;
    }
    
    final inputImage = InputImage.fromFile(_imageFile!);

    try {
      final result = await _textRecognizer.processImage(inputImage);
      _recognizedText = result.text.isEmpty ? '' : result.text;
      setState(() {
        _contentController.text += (_contentController.text.isEmpty ? '' : '\n') + _recognizedText;
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('识别失败: $e')),
        );
      }
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _labelController.dispose();
    _recorder.closeRecorder();
    _player.dispose();
    _speech.cancel();
    _textRecognizer.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        title: Text(widget.note == null ? '新建笔记' : '编辑笔记'),
        actions: [
          IconButton(
            icon: const Icon(Icons.folder),
            onPressed: () async {
              await _selectFolder();
            },
          ),
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: () => _saveNote(),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Card(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              child: TextField(
                controller: _titleController,
                style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
                decoration: const InputDecoration(
                  hintText: '标题',
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.all(16),
                ),
              ),
            ),
            Text(_selectedFolderId == '-1111' || _selectedFolderId == null ? '其他' : _folders.firstWhere((f) => f.id == _selectedFolderId).name, style: const TextStyle(color: Colors.grey)),
            Card(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              child: Column(
                children: [
                  TextField(
                    controller: _contentController,
                    style: const TextStyle(fontSize: 16, height: 1.5),
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.all(16),
                    ),
                    maxLines: 21,
                  ),
                  if (_isListening)
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      '正在识别: $_lastWords',
                      style: const TextStyle(fontStyle: FontStyle.italic, color: Colors.grey),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            Card(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  children: [
                    const Icon(Icons.label_outline, color: Colors.grey),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextField(
                        controller: _labelController,
                        style: const TextStyle(fontSize: 16),
                        maxLength: 1,
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp('[ABCD123456789]'))
                        ],
                        decoration: const InputDecoration(
                          hintText: '标签(A~D, 1~9)',
                          counterText: '',
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(vertical: 16),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (_imagePaths.isNotEmpty) 
            ListView.builder(
              shrinkWrap: true, 
              physics: const NeverScrollableScrollPhysics(), 
              itemCount: _imagePaths.length,
              itemBuilder: (context, index) {
                String imagePath = _imagePaths[index];     
                return Stack( 
                  children: [
                    Padding( 
                      padding: const EdgeInsets.all(8.0),
                      child: Image.file( 
                        File(imagePath),
                        fit: BoxFit.contain, 
                      ),
                    ),
                    Positioned( 
                      right: 0,
                      top: 0,
                      child: IconButton(
                        icon: const Icon(Icons.close, color: Colors.grey),
                        onPressed: () => _removeImage(index),
                      ),
                    ),
                  ],
                );
              },
            ),
            if (_audioPaths.isNotEmpty)
            ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: _audioPaths.length,
              itemBuilder: (context, index) {
                return ListTile(
                  leading: const Icon(Icons.multitrack_audio),
                  title: Text('录音 ${index + 1}'),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: Icon(_currentPlayingPath == _audioPaths[index] ? Icons.pause : Icons.play_arrow),
                        onPressed: () {
                          final audioPath = _audioPaths[index];
                          if (_currentPlayingPath == audioPath) {
                            if (_player.state == PlayerState.playing) {
                              _player.pause();
                            } else if (_player.state == PlayerState.paused) {
                              _player.resume();
                            } else {
                              _playAudio(audioPath);
                            }
                          } else {
                            setState(() { _currentPlayingPath = audioPath; }); 
                            _playAudio(audioPath);
                          }
                          setState(() {});
                        },
                      ),
                      IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () => _removeAudio(index),
                      ),
                    ],
                  ),
                );
              },
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            TextButton(
              onPressed: () async {
                final result = await _showImageSourceDialog();
                if (result != null) {
                  _pickImage(result);
                }
              },
              child: const Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.image),
                  Text('图片', style: TextStyle(fontSize: 12),),
                ],
              )
            ),
            const VerticalDivider(
              thickness: 1,
              color: Colors.grey,
            ),
            TextButton(
              onPressed: _isRecording ? _stopRecording : _startRecording,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon( _isRecording ? Icons.stop : Icons.mic),
                  const Text('录音', style: TextStyle(fontSize: 12),),
                ],
              )
            ),
            const VerticalDivider(
              thickness: 1,
              color: Colors.grey,
            ),
            TextButton(
              onPressed: _isListening ? _stopListening :  _startListening,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(_isListening ? Icons.stop : Icons.text_fields, color: _isListening ? Colors.red : null,),
                  const Text('语音转文字', style: TextStyle(fontSize: 12),),
                ],
              )
            ),
            const VerticalDivider(
              thickness: 1,
              color: Colors.grey,
            ),
            TextButton(
              onPressed: () async {
                final result = await _showImageSourceDialog();
                if (result != null) {
                _recognize(result);
                }
              },
              child: const Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.document_scanner),
                  Text('文档扫描', style: TextStyle(fontSize: 12),),
                ],
              )
            ),
          ],
        ),
      ),
    );
  }
}
